<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\User;

class UploadController extends Controller 
{
	/**
     * 上传头像
     * @param \Illuminate\Http\Request $request
     * @return mixed|\Illuminate\Http\JsonResponse
     */
    public function uploadAvatar(Request $request)
    {
        $request->validate([
            'avatar' => 'required|image|mimes: jpeg,png,jpg,gif|max:2048'
        ]);
        try{
            $file = $request->file('avatar');
            // 生成文件名
            $fileName = 'avatar_' . time() . '.' . $file->getClientOriginalExtension();
            // 保存文件到存储路径
            $path = $file->storeAs('avatars', $fileName, 'public');

            $user = User::find(1);
            if($user->avatar && Storage::disk('public')->exists($user->avatar)) {
                // 删除旧头像
                Storage::disk('public')->delete($user->avatar);
            }

            // 更新用户头像路径
            $user->update(['avatar' => $path]);
            return response()->json([
                'data' => [
                    'avatar_url' => asset('storage/'. $path),
                    'avatar_path' => $path,
                ],
                'message' => '头像上传成功',
            ], 200);

        }catch (\Exception $e){
            return response()->json([
                'message' => '头像上传失败' . $e->getMessage()
            ], 500);
        }
    }
    /**
     * 上传文章封面
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadCover(Request $request)
    {
        $request->validate([
            'cover' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
        ], [
            'cover.required' => '请上传封面图片',
            'cover.image' => '文件必须为图片',
            'cover.mimes' => '仅支持 jpeg,png,jpg,gif,webp 格式',
            'cover.max' => '图片大小不能超过 2MB',
        ]);

        try{
            $file = $request->file('cover');
            $fileName = 'cover_' . auth('sanctum')->id() . '_' . time() . '.' . '.webp';
            $path = 'covers/' . date('Y/m') . '/' . $fileName;

            // 压缩并转为 WebP
            $image = ImageFacade::make($file)
                ->resize(1200, null, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                })
                ->encode('webp', 80);
            Storage::disk('public')->put($path, $image);

            // 记录到 images 表
            $imageRecord = Image::create([
                'url' => asset('storage/' . $path),
                'path' => $path,
                'user_id' => auth('sanctum')->id(),
                'type' => 'cover',
                'status' => 'temporary',
            ]);

            return response()->json([
                'data' => [
                    'cover_url' => $imageRecord->url,
                    'cover_id' => $imageRecord->id,
                    'cover_path' => $path,
                ],
                'message' => '封面上传成功',
            ], 200);

        } catch (\Exception $e){
            return response()->json([
                'message' => '封面上传失败' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 上传内容图片
     */
    public function uploadImage(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:2048',
        ], [
            'image.required' => '请上传图片',
            'image.image' => '文件必须为图片',
            'image.mimes' => '仅支持 jpeg,png,jpg,gif,webp 格式',
            'image.max' => '图片大小不能超过 2MB',
        ]);

        try {
            $file = $request->file('image');
            $fileName = 'image_' . auth('sanctum')->id() . '_' . time() . '.webp';
            $path = 'images/' . date('Y/m') . '/' . $fileName;

            // 压缩并转为 WebP
            $image = ImageFacade::make($file)
                ->resize(1200, null, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                })
                ->encode('webp', 80);
            Storage::disk('public')->put($path, $image);

            // 记录到 images 表
            $imageRecord = Image::create([
                'url' => asset('storage/' . $path),
                'path' => $path,
                'user_id' => auth('sanctum')->id(),
                'type' => 'content',
                'status' => 'temporary',
            ]);

            return response()->json([
                'data' => [
                    'image_url' => $imageRecord->url,
                    'image_id' => $imageRecord->id,
                    'image_path' => $path,
                ],
                'message' => '图片上传成功',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => '图片上传失败: ' . $e->getMessage()
            ], 500);
        }
    }

    
    /**
     * 清理未使用的图片
     */
    public function cleanUnusedImages(Request $request)
    {
        try {
            // 确保只有授权用户可以清理（可根据需要添加权限控制）
            $request->user('sanctum')->id();

            // 查询 7 天前的临时图片
            $images = Image::where('status', 'temporary')
                ->where('created_at', '<', now()->subDays(7))
                ->where('user_id', auth('sanctum')->id()) // 限制为当前用户
                ->get();

            $deletedCount = 0;
            foreach ($images as $image) {
                Storage::disk('public')->delete($image->path);
                $image->delete();
                $deletedCount++;
            }

            return response()->json([
                'data' => [
                    'deleted_count' => $deletedCount,
                ],
                'message' => "已清理 {$deletedCount} 张未使用图片",
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => '清理图片失败: ' . $e->getMessage()
            ], 500);
        }
    }
}
